import { defineConfig, loadEnv } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";
const path = require("path");
function pathResolve(dir) {
  return resolve(__dirname, ".", dir);
}
// Element 按需加载配置
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

// import.meta.env.VITE_API_URL env 使用语法
// npm i vite-plugin-compression -D gzip 压缩
// cnpm i vite-plugin-imagemin -D 图片压缩  这包很难下载(注:尽量用cnpm 下载)
export default defineConfig(({ mode }) => {
  const config = loadEnv(mode, "./");
  console.log(config, "[][]");
  return {
    plugins: [
      vue(),
      // ... Element 按需加载
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    // 为了兼容Linux系统 最好使用相对路径
    base: "./",
    // 起别名
    resolve: {
      alias: {
        "@": pathResolve("src"),
        // 键必须以斜线开始和结束
        // "/@/": path.resolve(__dirname, "./src"),
      },
    },
    server: {
      host: "0.0.0.0", //这里是服务器ip 写出0.0.0.就可以
      port: 80,
      open: true, // 自动运行在浏览器中
      proxy: {
        //跨域代理 api 还有rewrite里面的api 改成自己项目里面的
        "/api": {
          target: config.VITE_APP_API_URL,
          ws: true,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
        // 测试多个跨域
        "/apiInfo": {
          target: config.VITE_APP_INFO_API_URL,
          ws: true,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    // 线上环境移除console日志
    build: {
      minify: "terser", // 需要加上这个才生效
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
        ie8: true,
        output: {
          comments: true,
        },
      },
      outDir: "dist", // 打包输出是文件名
      sourcemap: false, //线上环境关闭 HTML注释
      chunkSizeWarningLimit: 1500, // 大小警告的限制 模式是500 （以 kbs 为单位）
      // 打包时 把资源分类
      rollupOptions: {
        output: {
          entryFileNames: `js/[name]-[hash].js`,
          chunkFileNames: `js/[name]-[hash].js`,
          assetFileNames: `[ext]/[name]-[hash].[ext]`,
        },
      },
    },
  };
});
